import os

import yaml
from conf.setting import BASE_PATH


class Yaml(object):
    def __init__(self, file_path):
        self.file_path = file_path

    def read_yml(self, key=None):
        """

        @param key:
        @return:
        """
        with open(os.path.join(BASE_PATH, self.file_path), mode="r", encoding="utf-8") as f:
            result = yaml.load(stream=f, Loader=yaml.SafeLoader)
            if not result:
                return dict()
            if key:
                return result.get(key)
            return result

    def write_yml(self, key, value):
        """

        @param key:
        @param value:
        @return:
        """
        result = self.read_yml()
        result[key] = value
        with open(os.path.join(BASE_PATH, self.file_path), mode="w", encoding="utf-8") as f:
            yaml.dump(result, f, allow_unicode=True)

    def clean_yml(self):
        with open(os.path.join(BASE_PATH, self.file_path), mode="w", encoding="utf-8") as f:
            f.truncate()
